/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { error } from 'cc';
import { conflict } from './base';
import { pipeline } from './pipeline';

const TAG = 'lcc/core/request.ts';

/**
 * @zh
 * 请求选项
 */
export interface RequestOptions {
    /**
     * 自定义子协议
     */
    subproto?: string;

    /**
     * 自定义管道
     */
    pipelines?: string[];
}

/**
 * @zh
 * 请求协议
 */
export interface RequestProtocol {
    /**
     * @zh
     * GET 请求
     *
     * @param mainproto 主协议
     * @param subproto 子协议
     * @param path 路径
     * @param options 可选，附件参数
     * @requires R 请求结果
     */
    get?: (mainproto: string, subproto: string, path: string, options?: RequestOptions) => Promise<any>;

    /**
     * @zh
     * POST 请求
     *
     * @param mainproto 主协议
     * @param subproto 子协议
     * @param path 路径
     * @param data 数据
     * @param options 可选，附件参数
     * @requires R 请求结果
     */
    post?: (mainproto: string, subproto: string, path: string, data: any, options?: RequestOptions) => Promise<any>;

    /**
     * @zh
     * DELETE 请求
     *
     * @param mainproto 主协议
     * @param subproto 子协议
     * @param path 路径
     * @param options 可选，附件参数
     * @requires boolean 是否成功
     */
    delete?: (mainproto: string, subproto: string, path: string, options?: RequestOptions) => Promise<boolean>;
}

/**
 * @zh
 * 请求模块<br/>
 *
 * 主要用于抽象游戏中的IO操作，类似于HTTP请求方式。<br/>
 * 但是添加了处理管道功能。格式如下；<br/>
 * <主协议>[-子协议][|处理管道1][|处理管道2 ...]://<路径> <br/>
 * 比如：http|json://localhost:8080/test/config.json, 返回为JSON对象 <br/>
 * 子协议用于自定义使用
 */
class Request {
    /**
     * @zh
     * 静态对象
     */
    private static _instance: Request = null!;

    /**
     * @zh
     * 获得单例对象
     */
    static get instance() {
        if (Request._instance === null) {
            Request._instance = new Request();
        }
        return Request._instance;
    }

    /**
     * 构造函数
     */
    private constructor() {}

    /**
     * @zh
     * 协议映射表
     */
    private _protocolMap: { [key: string]: RequestProtocol } = Object.create(null);

    /**
     * @zh
     * 注册请求协议
     *
     * @param name 协议名称
     * @param protocol 协议接口
     * @param override 是否覆盖
     */
    register(name: string, protocol: RequestProtocol, override = false) {
        if (!override && this._protocolMap[name]) {
            conflict(TAG, `protocol ${name} conflict`);
        }
        this._protocolMap[name] = protocol;
    }

    /**
     * @zh
     * GET 请求
     *
     * @param url URL路径
     * @param options 可选，附件参数，附件管线pipelines优先于路径中的管线
     * @returns Promise<any> 内容
     */
    async get<R = any>(url: string, options?: RequestOptions) {
        // 解析协议头和路径
        let pi = url.indexOf('://');
        if (pi === -1) {
            error(TAG, `url ${url} proto not found!`);
            return null;
        }
        let head = url.substring(0, pi);
        let path = url.substring(pi + 3, url.length);

        // 解析协议名称和管道数组
        let [proto, ...pipelines] = head.split('|');

        // 解析主协议和子协议
        let [mainproto, subproto] = proto.split('-');

        let protocol = this._protocolMap[mainproto];
        if (!protocol) {
            error(TAG, `protocol ${mainproto} not found!`);
            return null;
        }

        if (!protocol.get) {
            error(TAG, `protocol ${mainproto} has not GET method!`);
            return null;
        }

        /** 结果 */
        let result = await protocol.get(mainproto, subproto, path, options);

        // 管道处理结果，优先使用options中的管道
        result = await pipeline.handle(result, options?.pipelines || pipelines);

        return result as R;
    }

    /**
     * @zh
     * POST 请求
     *
     * @param url URL路径
     * @param data 数据
     * @param options 可选，附件参数，附件管线pipelines优先于路径中的管线
     * @returns Promise<any> 内容
     */
    async post<R = any>(url: string, data: any, options?: RequestOptions) {
        // 解析协议头和路径
        let pi = url.indexOf('://');
        if (pi === -1) {
            error(TAG, `url ${url} proto not found!`);
            return null;
        }
        let head = url.substring(0, pi);
        let path = url.substring(pi + 3, url.length);

        // 解析协议名称和管道数组
        let [proto, ...pipelines] = head.split('|');

        // 解析主协议和子协议
        let [mainproto, subproto] = proto.split('-');

        let protocol = this._protocolMap[mainproto];
        if (!protocol) {
            error(TAG, `protocol ${mainproto} not found!`);
            return null;
        }

        if (!protocol.post) {
            error(TAG, `protocol ${mainproto} has not POST method!`);
            return null;
        }

        /** 结果 */
        let result = await protocol.post(mainproto, subproto, path, data, options);

        // 管道处理结果，优先使用options中的管道
        result = await pipeline.handle(result, options?.pipelines || pipelines);

        return result as R;
    }

    /**
     * @zh
     * DELETE 请求<br/>
     * 注意：由于没有可变返回值忽略管道处理
     *
     * @param url URL路径
     * @param options 可选，附件参数
     * @returns Promise<any> 内容
     */
    async delete(url: string, options?: RequestOptions) {
        // 解析协议头和路径
        let pi = url.indexOf('://');
        if (pi === -1) {
            error(TAG, `url ${url} proto not found!`);
            return null;
        }
        let head = url.substring(0, pi);
        let path = url.substring(pi + 3, url.length);

        // 解析协议名称
        let [proto] = head.split('|');

        // 解析主协议和子协议
        let [mainproto, subproto] = proto.split('-');

        let protocol = this._protocolMap[mainproto];
        if (!protocol) {
            error(TAG, `protocol ${mainproto} not found!`);
            return false;
        }

        if (!protocol.delete) {
            error(TAG, `protocol ${mainproto} has not DELETE method!`);
            return false;
        }

        /** 结果 */
        let result = await protocol.delete(mainproto, subproto, path, options);

        return result;
    }
}

/**
 * @zh
 * 请求对象
 */
export const request = Request.instance;
